const axios = require('axios');
const db = require('../config/db');

// 钉钉机器人 Webhook 地址
const DINGTALK_ACCESS_TOKEN = process.env.DINGTALK_ACCESS_TOKEN;
const DINGTALK_WEBHOOK = `https://oapi.dingtalk.com/robot/send?access_token=${DINGTALK_ACCESS_TOKEN}`;

/**
 * 发送钉钉通知
 * @param {Object} memo - 备忘录对象
 * @param {Object} user - 用户对象
 */
async function sendDingTalkNotification(memo, user) {
  try {
    const priorityMap = {
      high: '🔴 高',
      medium: '🟡 中',
      low: '🟢 低'
    };

    const priority = priorityMap[memo.priority] || '🟡 中';

    // 格式化提醒时间
    const remindTime = new Date(memo.remind_time).toLocaleString('zh-CN', {
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });

    // 移除HTML标签，获取纯文本内容
    const content = memo.content.replace(/<[^>]*>/g, '').trim();

    const message = {
      msgtype: 'markdown',
      markdown: {
        title: '备忘录通知',
        text: `#### 📝 备忘录通知\n\n` +
          `**用户：** ${user.username || user.email}\n\n` +
          `**优先级：** ${priority}\n\n` +
          `**提醒时间：** ${remindTime}\n\n` +
          `**内容：** ${content}\n\n` +
          `---\n\n` +
          `> 请及时处理您的备忘事项`
      }
    };

    const response = await axios.post(DINGTALK_WEBHOOK, message, {
      headers: {
        'Content-Type': 'application/json'
      },
      timeout: 5000
    });

    if (response.data.errcode === 0) {
      console.log(`✅ 推送成功 - 备忘录ID: ${memo.id}, 用户: ${user.email}`);
      return true;
    } else {
      console.error(`❌ 推送失败 - 备忘录ID: ${memo.id}, 错误: ${response.data.errmsg}`);
      return false;
    }
  } catch (error) {
    console.error(`❌ 推送异常 - 备忘录ID: ${memo.id}, 错误:`, error.message);
    return false;
  }
}

/**
 * 检查并推送到期的备忘录
 */
async function checkAndPushReminders() {
  try {
    // 获取当前时间（中国时区 UTC+8）
    const now = new Date();

    // 查询需要推送的备忘录：
    // 1. 未完成 (completed = 0)
    // 2. 未删除 (is_deleted = 0)
    // 3. 未推送 (is_pushed = 0)
    // 4. 提醒时间 <= 当前时间
    const sql = `
      SELECT m.*, u.email, u.username
      FROM memos m
      JOIN users u ON m.user_id = u.id
      WHERE m.completed = 0
        AND m.is_deleted = 0
        AND m.is_pushed = 0
        AND m.remind_time <= CONVERT_TZ(NOW(), '+00:00', '+08:00')
      ORDER BY m.priority DESC, m.remind_time ASC
    `;

    const [memos] = await db.query(sql);

    if (memos.length === 0) {
      console.log(`⏰ [${now.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}] 没有需要推送的备忘录`);
      return;
    }

    console.log(`⏰ [${now.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}] 发现 ${memos.length} 条待推送备忘录`);

    // 逐个推送
    for (const memo of memos) {
      const user = {
        email: memo.email,
        username: memo.username
      };

      const success = await sendDingTalkNotification(memo, user);

      // 无论推送成功与否，都标记为已推送，避免重复推送
      // 如果需要失败重试，可以修改这里的逻辑
      if (success) {
        await db.query(
          'UPDATE memos SET is_pushed = 1, pushed_at = NOW() WHERE id = ?',
          [memo.id]
        );
      }

      // 避免频繁请求，每次推送间隔100ms
      await new Promise(resolve => setTimeout(resolve, 100));
    }

    console.log(`✅ 推送任务完成`);
  } catch (error) {
    console.error('❌ 检查推送任务出错:', error);
  }
}

module.exports = {
  checkAndPushReminders,
  sendDingTalkNotification
};
